//
//  MFWUserLoginManager.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-8-6.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "MFWUserLoginManager.h"
#import "MFWSDKNotificationConsts.h"
#import "MULLoginManager.h"

NSString *const kMFWLoginError_Str_Msg =kMULLoginErrorMessage;
NSString *const kMFWLoginError_Domain = kMULLoginErrorDomain;

 NSString *const MFWErrorDomain;
 NSString *const kMFWErrorInfo_Str_Msg;// key in http error info dictionay -> error msg
 NSString *const kMFWErrorInfo_Int_StatusCode;// key in http error info dictionary -> http response status code


@interface MFWSdkEnvironment()
@end

@interface MFWUserLoginManager()
@property(nonatomic, copy)UserLoginFinished loginCallback;
@property(nonatomic, copy)UserRegisterFinished registerCallback;
@property(nonatomic, copy)UserLoginFinished thirdPartLoginCallback;
@end

@implementation MFWUserLoginManager

+ (MFWUserLoginManager *)sharedInstance;
{
    static MFWUserLoginManager *_sharedInstance = nil;
	if (_sharedInstance == nil)
	{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedInstance = [[MFWUserLoginManager alloc] init];
			
        });
	}
	
	return _sharedInstance;
}

+ (void)setThirdPartBindingNavigationConfigBlock:(void(^)(UINavigationController *navigationController)) block;
{
    [MULLoginManager sharedInstance].bindNavigationConfigBlock = block;
}

- (void)logout;
{
//    [self logoutCurrentUser];
    [[NSNotificationCenter defaultCenter] postNotificationName:kSDK_Notify_UserWillLogout object:nil];
}

- (void)accessTokenFinised:(NSData*)responseData parsedJson:(MFWJson*)json error:(NSError*)error
{

    if (json && !error)
    {
//        error = [MFWServiceUtils parseMFWServiceError:json];
    }
    
    if (error)
    {// obtain accesstoken failed
        if (self.loginCallback)
        {
            if ([error.userInfo intValueForKey:kMFWErrorInfo_Int_StatusCode] == 401)
            {
                error = [NSError errorWithDomain:MFWErrorDomain code:10000 userInfo:@{kMFWErrorInfo_Int_StatusCode: @401, kMFWErrorInfo_Str_Msg : @"用户名或密码错误"}];
            }
            self.loginCallback(NO, nil, error);
            
            self.loginCallback = nil;
        }
    }
    else
    {// obtain accessToken and user info successfull
        if ([self handleUserTokenSucc:json])
        {
            if (self.loginCallback)
            {
                self.loginCallback(YES, [MFWSdkEnvironment sharedInstance].userInfo, nil);
                
                self.loginCallback = nil;
            }
        }
        else if (self.loginCallback)
        {
            self.loginCallback(NO, nil, nil);
            
            self.loginCallback = nil;
        }
    }
}

- (void)thirdPartLoginFinished:(NSData*)responseData parsedJson:(MFWJson*)json error:(NSError*)error
{
    if (json && !error)
    {
//        error = [MFWServiceUtils parseMFWServiceError:json];
    }
    
    if (error)
    {// obtain accesstoken failed
        if (self.thirdPartLoginCallback)
        {
            if ([error.userInfo intValueForKey:kMFWErrorInfo_Int_StatusCode] == 401)
            {
                error = [NSError errorWithDomain:MFWErrorDomain code:10000 userInfo:@{kMFWErrorInfo_Int_StatusCode: @401, kMFWErrorInfo_Str_Msg : @"用户名或密码错误"}];
            }
            self.thirdPartLoginCallback(NO, nil, error);
            
            self.thirdPartLoginCallback = nil;
        }
    }
    else
    {// obtain accessToken and user info successfull
        if ([self handleUserTokenSucc:json])
        {
            if (self.thirdPartLoginCallback)
            {
                self.thirdPartLoginCallback(YES, [MFWSdkEnvironment sharedInstance].userInfo, nil);
                
                self.thirdPartLoginCallback = nil;
            }
        }
        else if (self.thirdPartLoginCallback)
        {
            self.thirdPartLoginCallback(NO, nil, nil);
            
            self.thirdPartLoginCallback = nil;
        }
    }

}

- (void)accountRegisterFinished:(NSData*)responseData parsedJson:(MFWJson*)json error:(NSError*)error
{
    if (json && !error)
    {
//        error = [MFWServiceUtils parseMFWServiceError:json];
    }
    
    if (error)
    {// obtain accesstoken failed
        if (self.registerCallback)
        {
            if ([error.userInfo intValueForKey:kMFWErrorInfo_Int_StatusCode] == 401)
            {
                error = [NSError errorWithDomain:MFWErrorDomain code:10000 userInfo:@{kMFWErrorInfo_Int_StatusCode: @401, kMFWErrorInfo_Str_Msg : @"用户名或密码错误"}];
            }
            self.registerCallback(NO, nil, error);
            
            self.registerCallback = nil;
        }
    }
    else
    {// obtain accessToken and user info successfull
        if ([self handleUserTokenSucc:json])
        {
            if (self.registerCallback)
            {
                self.registerCallback(YES, [MFWSdkEnvironment sharedInstance].userInfo, nil);
                
                self.registerCallback = nil;
            }
        }
        else if (self.registerCallback)
        {
            self.registerCallback(NO, nil, nil);
            
            self.registerCallback = nil;
        }
            
    }
}

- (BOOL)handleUserTokenSucc:(MFWJson*)json
{
    MFWJson *jsonData = [json jsonForKey:@"data"];
    
    [[MFWSdkEnvironment sharedInstance].userInfo updateInfoFromUserJsonData:jsonData];
    
//    NSString *oauthToken = [jsonData stringValueForKey:@"oauth_token"];
//    NSString *oauthSecret = [jsonData stringValueForKey:@"oauth_token_secret"];
//    NSString *uid = [MFWSdkEnvironment sharedInstance].userInfo.uid;
    
    
    
    // login success
    [[NSNotificationCenter defaultCenter] postNotificationName:kSDK_Notify_UserDidLogin object:nil userInfo:jsonData.jsonObj];
    
    return YES;
}

- (MFWUserInfo*)parseUserInfo:(NSDictionary*)baseInfo extraInfo:(NSDictionary*)extraInfo
{
    if (!baseInfo && !extraInfo)
    {
        return nil;
    }
    
    MFWUserInfo *userInfo = [MFWSdkEnvironment sharedInstance].userInfo;
    userInfo.uid = [baseInfo stringValueForKey:@"id"];
    userInfo.nickName = [baseInfo stringValueForKey:@"username"];
    userInfo.logoUrl = [baseInfo stringValueForKey:@"icon"];
    if (extraInfo)
    {
        userInfo.logoUrl = [extraInfo stringValueForKey:@"header"];
        userInfo.gender = [extraInfo intValueForKey:@"gender"];
        userInfo.ucity = [extraInfo stringValueForKey:@"location"];
        userInfo.uIntro = [extraInfo stringValueForKey:@"desc"];
    }
     
    if ([userInfo.uid length] > 0)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [userInfo synchronizeToDisk];
        });
    }

    [MFWSdkEnvironment sharedInstance].accessToken = [baseInfo stringValueForKey:@"oauth_token"];
    [MFWSdkEnvironment sharedInstance].tokenSecret = [baseInfo stringValueForKey:@"oauth_token_secret"];
    
    return userInfo;
}

- (BOOL)loginWithMFWUserName:(NSString*)username password:(NSString*)password finisheHandler:(UserLoginFinished)handler;
{
    
    if ([NSString isEmptyString:username] || [NSString isEmptyString:password])
    {
        return NO;
    }
    
    self.loginCallback = handler;
    
    __weak MFWUserLoginManager* wself = self;
    [[MULLoginManager sharedInstance] loginWithMFWAccount:username
                                                 password:password
                                                 openUDID:[MFWSdkEnvironment sharedInstance].openUDID
                                            finishedBlock:^(BOOL success, NSDictionary *baseInfo, NSDictionary *extraInfo, NSError *error) {
        
        MFWUserLoginManager *sself = wself;
        if (sself)
        {
            MFWUserInfo *userInfo = [self parseUserInfo:baseInfo extraInfo:extraInfo];
            
            sself.loginCallback(!error, userInfo, error);
            
            if (!error)
            {
                // login success
                [[NSNotificationCenter defaultCenter] postNotificationName:kSDK_Notify_UserDidLogin object:nil userInfo:baseInfo];
            }
        }
    }];
    
    return YES;
}

- (BOOL)do3rdLoginWithUid:(NSString*)userid
                     type:(NSString*)type
                     name:(NSString*)name
                   header:(NSString*)header
                 location:(NSString*)location
                   gender:(NSString*)gender
                  unionId:(NSString*)unionId
            finishHandler:(UserLoginFinished) handler {
    if ([NSString isEmptyString:userid] || [NSString isEmptyString:type])
    {
        return NO;
    }
    
    self.loginCallback = handler;
    
    __weak MFWUserLoginManager* wself = self;
    [[MULLoginManager sharedInstance] loginWith3rdUid:userid type:type name:name header:header location:location gender:gender                unionId:unionId                            finishedBlock:^(BOOL success, NSDictionary *baseInfo, NSDictionary *extraInfo, NSError *error) {
                                                
                                                MFWUserLoginManager *sself = wself;
                                                if (sself)
                                                {
                                                    MFWUserInfo *userInfo = [self parseUserInfo:baseInfo extraInfo:extraInfo];
                                                    sself.loginCallback(!error, userInfo, error);
                                                    
                                                    if (!error)
                                                    {
                                                        // login success
                                                        [[NSNotificationCenter defaultCenter] postNotificationName:kSDK_Notify_UserDidLogin object:nil userInfo:baseInfo];
                                                    }
                                                }
                                            }];
    
    return YES;
}



- (BOOL)loginWithPhone:(NSString *)phone messageNumber:(NSString *)messageNumber finisheHandler:(UserLoginFinished)handler{
    if ([NSString isEmptyString:phone] || [NSString isEmptyString:messageNumber])
    {
        return NO;
    }
    self.loginCallback = handler;
    
    __weak MFWUserLoginManager* wself = self;
    [[MULLoginManager sharedInstance] loginWithPhoneNumber:phone message:messageNumber finishedBlock:^(BOOL success, NSDictionary *baseInfo, NSDictionary *extraInfo, NSError *error) {
        MFWUserLoginManager *sself = wself;
        if (sself)
        {
            MFWUserInfo *userInfo = [self parseUserInfo:baseInfo extraInfo:extraInfo];
            
            sself.loginCallback(!error, userInfo, error);
            
            if (!error)
            {
                // login success
                [[NSNotificationCenter defaultCenter] postNotificationName:kSDK_Notify_UserDidLogin object:nil userInfo:baseInfo];
            }
        }
    }];
    return YES;
}

-(BOOL)loginWithOIDUserName:(NSString *)username password:(NSString *)password finisheHandler:(UserLoginFinished)handler{
    if ([NSString isEmptyString:username] || [NSString isEmptyString:password])
    {
        return NO;
    }
    
    self.loginCallback = handler;
    
    __weak MFWUserLoginManager* wself = self;
    [[MULLoginManager sharedInstance] loginWithMFWAccount:username
                                                 password:password
                                                 openUDID:nil
                                            finishedBlock:^(BOOL success, NSDictionary *baseInfo, NSDictionary *extraInfo, NSError *error) {
                                                
                                                MFWUserLoginManager *sself = wself;
                                                if (sself)
                                                {
                                                    MFWUserInfo *userInfo = [self parseUserInfo:baseInfo extraInfo:extraInfo];
                                                    
                                                    sself.loginCallback(!error, userInfo, error);
                                                    
                                                    if (!error)
                                                    {
                                                        // login success
                                                        [[NSNotificationCenter defaultCenter] postNotificationName:kSDK_Notify_UserDidLogin object:nil userInfo:baseInfo];
                                                    }
                                                }
                                            }];
    
    return YES;

}

- (BOOL)registerWithOIDUserName:(NSString*)username password:(NSString*)password email:(NSString *)email finisheHandler:(UserRegisterFinished)handler{
    if ([NSString isEmptyString:username] || [NSString isEmptyString:password])
    {
        return NO;
    }
    
    self.registerCallback = handler;
    
    __weak MFWUserLoginManager* wself = self;
    [[MULLoginManager sharedInstance] registerWithMFWAccount:username password:password nickName:nil
                                                    openUDID:nil
                                                       email:email
                                               finishedBlock:^(BOOL success, NSDictionary *baseInfo, NSDictionary *extraInfo, NSError *error) {
                                                   
                                                   MFWUserLoginManager *sself = wself;
                                                   if (sself)
                                                   {
                                                       MFWUserInfo *userInfo = [self parseUserInfo:baseInfo extraInfo:extraInfo];
                                                       sself.registerCallback(!error, userInfo, error);
                                                       
                                                       if (!error)
                                                       {
                                                           // login success
                                                           [[NSNotificationCenter defaultCenter] postNotificationName:kSDK_Notify_UserDidLogin object:nil userInfo:baseInfo];
                                                       }
                                                   }
                                               }];
    
    return YES;
}

- (BOOL)registerWithMFWUserName:(NSString*)username password:(NSString*)password nickName:(NSString*)nickName finisheHandler:(UserRegisterFinished)handler;
{
    if ([NSString isEmptyString:username] || [NSString isEmptyString:password])
    {
        return NO;
    }
    
    self.registerCallback = handler;
    
    __weak MFWUserLoginManager* wself = self;
    [[MULLoginManager sharedInstance] registerWithMFWAccount:username password:password nickName:nickName
                                               openUDID:[MFWSdkEnvironment sharedInstance].openUDID
                                                email:nil
                                               finishedBlock:^(BOOL success, NSDictionary *baseInfo, NSDictionary *extraInfo, NSError *error) {
        
        MFWUserLoginManager *sself = wself;
        if (sself)
        {
            MFWUserInfo *userInfo = [self parseUserInfo:baseInfo extraInfo:extraInfo];
            sself.registerCallback(!error, userInfo, error);
            
            if (!error)
            {
                // login success
                [[NSNotificationCenter defaultCenter] postNotificationName:kSDK_Notify_UserDidLogin object:nil userInfo:baseInfo];
            }
        }
    }];
    
    return YES;
}


@end
